<?php


namespace Convert\Controller;

use Think\Controller;
use Think\Model;

class BaseController extends Controller
{
    protected $db_config = array();

    public function _initialize()
    {

        if (!is_administrator()) {
            $this->error('非管理员不能操作');
        }

        $sub_menu =
            array(
                'left' =>
                    array(
                        array('tab' => 'home', 'title' => '首页', 'href' => U('Convert/index/index')),
                    ),
            );
        $this->assign('sub_menu', $sub_menu);
        $this->_init_config();
    }

    protected function _init_config()
    {
        if (ACTION_NAME != 'index') {
            $path = './Application/Convert/Data/db.json';

            if (IS_POST) {
                $db_config1 = array(
                    'db_type' => I('post.db_type', 'mysql', 'op_h'),
                    'db_user' => I('post.db_user', '', 'op_h'),
                    'db_pwd' => I('post.db_pwd', ''),
                    'db_host' => I('post.db_host', ''),
                    'db_port' => I('post.db_port', '3306'),
                    'db_name' => I('post.db_name', ''),
                    'db_charset' => I('post.db_charset', 'utf8'),
                    'db_prefix' => I('post.db_prefix', 'opensns_'),
                    'data_auth_key' => I('post.data_auth_key', ''),
                );

                if (!$this->is_config_empty($db_config1)) {
                    rmdirr('./Application/Convert/Data/');
                    mkdir('./Application/Convert/Data/');
                    $json = json_encode($db_config1);
                    file_put_contents($path, $json);
                }


                //  session('db_config', $db_config1);
            } else {
                $json = file_get_contents($path);
                $db_config1 = json_decode($json, true);
                // $db_config1 = session('db_config');
            }

            if ($this->is_config_empty($db_config1)) {
                $this->error('请填写数据连接');
            }


            if (empty($db_config1['data_auth_key'])) {
                $this->error('DATA_AUTH_KEY必填');
            }


            $this->db_config = $db_config1;

            $this->assign('db_config', $db_config1);

            $check = $this->M('member')->find();
            if (!$check) {
                $this->error('请检查数据库连接是否正确。');
            }

        }

    }


    protected  function is_config_empty($db_config1){
       if(!empty($db_config1['db_user']) && !empty($db_config1['db_host']) && !empty($db_config1['db_name']) && !empty($db_config1['data_auth_key'])){
           return false;
       }
        return true;
    }
    protected function M($table)
    {
        $db_config1 = $this->db_config;
        return M($table, $db_config1['db_prefix'], $db_config1);
    }

    protected function checkTableIsExist($table, $schema = '')
    {
        !$schema && $schema = C('DB_NAME');
        $count = M()->query("SELECT COUNT(*) as count FROM information_schema.tables WHERE table_schema = '" . $schema . "'  AND table_name = '" . C('DB_PREFIX') . $table . "';");
        return $count[0]['count'];
    }


    public function doConvert()
    {
        ini_set("memory_limit", "1000M");
        set_time_limit(0);
        $aMethod = I('get.table', '', 'text');
        if (!$aMethod) {
            $data['status'] = 0;
            $this->ajaxReturn($data);
        }

        if ($aMethod == 'finish') {
            $this->finish();
        }

        if (in_array($aMethod, use_V1(), true) || (in_array($aMethod, getSubByKey(application_table(), 'name'), true) && !in_array($aMethod, use_V2()))) {
            $this->useV1($aMethod);
        } else {
            $this->useV2($aMethod);
        }
    }


    public function useV2($current)
    {
        $next = $this->getNext($current);
        $return['status'] = 2;
        $return['info'] = '使用V2数据，转移成功。';
        $return['next'] = $next;
        $this->writeLog($current, $return['status'], $return['info']);
        $this->ajaxReturn($return);
    }

    private function useV1($table)
    {
        $newTable = $table;
        if (method_exists($this, 'getTableName')) {
            $newTable = $this->getTableName($table);
        }


        $next = $this->getNext($table);
        truncate_table($newTable);
        $data = $this->M($table)->select();
        $res = true;
        if ($this->checkTableIsExist($newTable) == 1) {
            if (!empty($data)) {
                $method_name = 'convert_' . $table;
                if (method_exists($this, $method_name)) {
                    $data = $this->$method_name($data);
                }

                $data = array_chunk($data, 100);
                foreach ($data as $v) {
                    $rs = M($newTable)->addAll($v);
                    $res = $res && $rs;
                }
            }

        } else {
            $res = false;
            $info = '该表不存在。';
        }

        if ($res) {
            $return['status'] = 1;
            $return['info'] = '使用V1数据，转移成功。';
            $return['next'] = $next;
            $this->writeLog($table, $return['status'], $return['info']);
            $this->ajaxReturn($return);
        } else {

            $return['status'] = 0;
            $return['info'] = $info ? $info : '转移失败。';
            $return['next'] = $next;
            $this->writeLog($table, $return['status'], $return['info']);
            $this->ajaxReturn($return);
        }
    }

    protected function writeLog($table, $status, $info = '')
    {
        $path = './Application/Convert/Data/' . strtolower(CONTROLLER_NAME) . '.json';
        $json = file_get_contents($path);
        $data = json_decode($json, true);
        $data[$table] = array('is_success' => $status, 'info' => $info);
        $json = json_encode($data);
        file_put_contents($path, $json);
    }

    public function finishConvert()
    {
        clean_all_cache();
       // $this->success('转移成功', get_nav_url(C('DEFUALT_HOME_URL')));
        $this->display('Public/finish');
    }

}